﻿using System;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.VersionControl.Controls;

namespace TfsComLib.FolderDiff
{
    public sealed class DialogFolderDiffInv : IDisposable
    {
        private readonly Form dialogFolderDiff;

        public DialogFolderDiffInv(VersionControlServer versionControlServer, ItemIdentifier item1, int version1,
            ItemIdentifier item2, int version2)
        {
            var controlsAssembly = Assembly.GetAssembly(typeof (ControlAddItemsExclude));
            var dialogFolderDiffType =
                controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.DialogFolderDiff");
            var folderDiffType = controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.FolderDiff");
            var ci = dialogFolderDiffType.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new[] {folderDiffType},
                null);
            var folderDiffInv = new FolderDiffInv(versionControlServer, item1, version1, item2, version2);
            dialogFolderDiff = (Form) ci.Invoke(new[] {folderDiffInv.FolderDiffObject});
        }

        public DialogFolderDiffInv(VersionControlServer versionControlServer, string localPath)
        {
            var controlsAssembly = Assembly.GetAssembly(typeof (ControlAddItemsExclude));
            var dialogFolderDiffType =
                controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.DialogFolderDiff");
            var folderDiffType = controlsAssembly.GetType("Microsoft.TeamFoundation.VersionControl.Controls.FolderDiff");
            var ci = dialogFolderDiffType.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new[] {folderDiffType},
                null);
            var folderDiffInv = new FolderDiffInv(versionControlServer, localPath);
            dialogFolderDiff = (Form) ci.Invoke(new[] {folderDiffInv.FolderDiffObject});
        }

        public DialogResult DialogResult { get; set; }

        #region IDisposable Members

        public void Dispose()
        {
            if (dialogFolderDiff != null)
                dialogFolderDiff.Dispose();
        }

        #endregion

        public void ShowDialog()
        {
            dialogFolderDiff.ShowDialog();
            DialogResult = dialogFolderDiff.DialogResult;
        }
    }
}